<?php

namespace App\Trip\Plane;

use App\Models\Plane\PlaneOrders\PlaneOrder;
use App\Trip\Passengers\OrderSubPassenger;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class OrderSelectedPassengers
{
    private PlaneOrder            $order_info;
    private array|null|Collection $input_passengers = null;
    /**
     * 已匹配的乘客
     * @var array
     */
    private array $matched_passengers;
    /**
     * @var Collection
     */
    private Collection $order_passengers;

    public function __construct(PlaneOrder $order_info, $passengers = null)
    {
        $this->order_info       = $order_info;
        $this->input_passengers = $passengers;// null is default order passengers
        $this->order_passengers = $this->order_info->passengers;
        $this->validPassengers();
    }

    private function validPassengers(): void
    {
        if (is_null($this->input_passengers)) {
            $this->matched_passengers = $this->order_passengers->toArray();
        } else {
            $this->matched_passengers = collect($this->order_passengers)->filter(function ($passenger) use (&$selected_order_passenger_types) {
                $passenger_ids = collect($this->input_passengers)->map(function ($passenger) {
                    if (Str::contains($passenger['passenger_id'], '_')) {
                        return $passenger['passenger_id'];
                    } else {
                        return OrderSubPassenger::buildSubPassengerId($passenger['passenger_id'], $passenger['sequence']);
                    }
                })->toArray();
                $isSelect      = in_array(OrderSubPassenger::buildSubPassengerId($passenger['passenger_id'], $passenger['sequence']), $passenger_ids);
                if ($isSelect) {
                    $selected_order_passenger_types[$passenger['passenger_type']] = $passenger['passenger_type'];
                }
                return $isSelect;
            })->toArray();
        }
    }

    public function isPartPassengers(): bool
    {
        // 传入了乘客 且乘客数量与订单乘客数量不一致
        return $this->input_passengers && count($this->matched_passengers) != $this->order_passengers->count();
    }

    /**
     * 获取订单的 子单号
     * @return array
     */
    public function getSubOutOrderIds(): array
    {
        return collect($this->getSelectedPassengers())->pluck('sub_out_order_id')->unique()->toArray();
    }

    public function getSelectedPassengers(): array
    {
        return $this->matched_passengers;
    }

    public function getSubSelectedPassengers(string $sub_out_order_id): array
    {
        return collect($this->getSelectedPassengers())->where('sub_out_order_id', $sub_out_order_id)->toArray();
    }
}